<?php

namespace App\Http\Controllers\Admin\UserManager;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Services\Tools\HelperService;
use Illuminate\Http\Request;    //引用http请求类
use App\Response\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;

class UserChangeController extends BaseController {


    /**
     * @api {get} /user-manager/user-change-log 会员更新日志
     * @apiVersion 0.1.0
     * @apiName 会员管理-会员更新日志
     * @apiGroup 会员管理
     *
     * @apiParam {int} user_code 用户编号 可选
     * @apiParam {string} nickname 昵称 可选
     * @apiParam {string} user_id 昵称 可选
     * @apiParam {int} type 1,2,3 1修改user_code 2修改昵称3 修改性别 昵称 可选
     * @apiParam {int} start_time 时间筛选 开始时间
     * @apiParam {int} end_time 时间筛选 结束时间
     * @apiParam {int} page 当前页数
     * @apiParam {int} perPage 分页容量 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
    "code": 200,
    "data": {
        "list": [
            {
                "user_id(用户id)": 642928,
                "change_from(修改前)": "0",
                "change_to(修改后)": "1",
                "type(1修改user_code2修改昵称3修改性别)": 3,
                "add_time(修改时间)": "2020-11-09 16:43:55",
                "nickname(当前昵称)": "气泡用户748438",
                "user_code(当前用户编号)": 748438
            }
        ],
        "meta": {
                "page": 1,
                "limit": 10,
                "next": null,
                "total": 1
            }
        }
     }
     *
     *
     */
    public function list(Request $request) {
        //参数校验
//        try {
            $validator= Validator::make($request->all(), [
                'perPage' => 'filled|numeric',
                'page' => 'filled|numeric',
                'user_code'=>'integer|min:1',
                'user_id'=>'integer|min:1',
                'type'=>'integer|in:1,2,3',
                'nickname'=>'string|max:255',
                'start_time'=>'integer|min:1',
                'end_time'=>'integer|min:1',
            ]);
            if ($validator->fails()) {
                throw new BasicException(10001, $validator->errors()->first());
            }
//        } catch (\Exception $e) {
//            throw new BasicException(10001, json_encode($e->errors()));
//        }

        $list = app('repo_user')->getUserChangeQueryList($request->input());

        return Response::sendList($list);
    }

    /**
     * @api {Get} /userChange/headChangeList 用户头像变更记录
     * @apiGroup 补充接口-平台审核
     *
     * @apiParam {Int} user_no 用户号
     * @apiParam {Int} status 状态：-1：不限制；0：待审核；1：已审核
     * @apiParam {Int} per_page 每页显示条数
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1,
    "user_id": 547182,
    "head_picture_old": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/android_images/547182/20191120121043_1574223041223.jpg", 原始头像
    "head_picture_new": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/android_images/547177/20200405001316_1586016795843577.jpg", 新头像
    "add_time": "2020-09-13 20:26:40", 变更时间
    "status": 0, 状态：0：待审核；1：已审核
    "user_no": 187698, 用户号
    "nickname": "✧≖◡✿殇" 用户昵称
    }
    ],
    "first_page_url": "http://local.qipaoadmin/userChange/headChangeList?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/userChange/headChangeList?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/userChange/headChangeList",
    "per_page": 20,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function headChangeList(Request $request)
    {
        $userNo = $request->user_no; //用户号
        $status = $request->status === null ? -1 : $request->status; //状态：-1：不限制；0：待审核；1：已审核
        $perPage = $request->per_page ?: 20; //每页显示条数

        $where = [];
        if ($userNo) {
            $user = app('model_user')->select('user_id')->where('user_no', $userNo)->where('deleted', 0)->first();
            if ($user) {
                $where['user_id'] = $user->user_id;
            } else {
                $where['user_id'] = 0;
            }
        }
        if ($status != '-1') {
            $where['status'] = $status;
        }
        $list = app('model_ac_user_head_change')->where($where)->orderBy('id', 'desc')->paginate($perPage);
        foreach ($list as &$v) {
            $v->add_time = date('Y-m-d H:i:s', $v->add_time);
            //查询用户昵称和用户号
            $userData = app('model_user_data')->select('user_code', 'nickname')->where('user_id', $v->user_id)->first();
            $v->user_no = $userData->user_code;
            $v->nickname = $userData->nickname;
        }
        return Response::sendData($list);
    }

    /**
     * @api {Put} /userChange/headAudit 头像审核
     * @apiGroup 补充接口-平台审核
     *
     * @apiParam {Int} id 记录id
     * @apiParam {Int} audit_res 审核结果：1：审核通过；0：审核拒绝/一键替换
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function headAudit(Request $request)
    {
        $id = $request->id;
        $auditRes = $request->audit_res; //审核结果：1：审核通过；0：审核拒绝/一键替换

        $record = app('model_ac_user_head_change')->select('id', 'user_id', 'status')->where('id', $id)->first();
        if (empty($record)) {
            throw new BasicException(10001);
        }
        if ($record->status != 0) {
            throw new BasicException(0, '状态不符，请刷新重试');
        }

        DB::beginTransaction();
        try {
            //将状态改为1已审核
            app('model_ac_user_head_change')->where('id', $id)->update(['status' => 1, 'audit_time' => time()]);
            if ($auditRes == '0') {
                //给用户随机设置一个头像
                app('model_user_data')->where('user_id', $record->user_id)->update(['head_picture' => HelperService::getRandomHeadPicture()]);
            }

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, "审核失败：{$e->getMessage()}");
        }
    }

    /**
     * @api {Get} /userChange/userPhotoList 用户照片墙照片列表
     * @apiGroup 补充接口-平台审核
     *
     * @apiParam {Int} user_no 用户号
     * @apiParam {Int} per_page 每页显示条数
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 10096,
    "user_id": 643613,
    "url": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/img/5c249cf31e15cdec03c595703a996642.jpeg",
    "add_time": "2021-05-21 14:07:31",
    "user_no": 5164698,
    "nickname": "终书萱5164698"
    },
    {
    "id": 10086,
    "user_id": 547900,
    "url": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/android_images/547179/20200312111437_1583982877534578.jpg",
    "add_time": "2021-05-07 15:45:44",
    "user_no": 617040,
    "nickname": "提莫队长呢"
    }
    ],
    "first_page_url": "http://local.qipaoadmin/userChange/userPhotoList?page=1",
    "from": 1,
    "last_page": 505,
    "last_page_url": "http://local.qipaoadmin/userChange/userPhotoList?page=505",
    "next_page_url": "http://local.qipaoadmin/userChange/userPhotoList?page=2",
    "path": "http://local.qipaoadmin/userChange/userPhotoList",
    "per_page": 20,
    "prev_page_url": null,
    "to": 20,
    "total": 10085
    }
    }
     */
    public function userPhotoList(Request $request)
    {
        $userNo = $request->user_no; //用户号
        $perPage = $request->per_page ?: 20; //每页显示条数

        $where = [];
        if ($userNo) {
            $user = app('model_user')->select('user_id')->where('user_no', $userNo)->where('deleted', 0)->first();
            if ($user) {
                $where['user_id'] = $user->user_id;
            } else {
                $where['user_id'] = 0;
            }
        }

        $list = app('model_user_photo')
            ->select('id', 'user_id', 'url', 'file_type', 'add_time')
            ->where($where)
            ->where('state', 1)
            ->orderBy('id', 'desc')
            ->paginate($perPage);
        foreach ($list as &$v) {
            $v->add_time = date('Y-m-d H:i:s', $v->add_time);
            //查询用户昵称和用户号
            $userData = app('model_user_data')->select('user_code', 'nickname')->where('user_id', $v->user_id)->first();
            $v->user_no = $userData->user_code;
            $v->nickname = $userData->nickname;
        }
        return Response::sendData($list);
    }

    /**
     * @api {Delete} /userChange/userPhotoDel 删除用户照片墙的照片
     * @apiGroup 补充接口-平台审核
     *
     * @apiParam {Int} id 记录id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
    }
     */
    public function userPhotoDel(Request $request)
    {
        $id = $request->id;

        $photo = app('model_user_photo')->where('id', $id)->first();
        if (empty($photo)) {
            throw new BasicException(10001);
        }

        $res = app('model_user_photo')->where('id', $id)->update(['state' => -1, 'delete_time' => time()]);
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '删除失败');
        }
    }

    /**
     * @api {Get} /userChange/userVideo 用户视频列表
     *
     * @apiGroup 补充接口-平台审核
     *
     * @apiParam {Int} user_no 用户号
     * @apiParam {Int} page 第几页
     * @apiParam {Int} per_page 每页显示条数
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "current_page": 1,
    "data": [
    {
    "id": 1,
    "user_id": 1296021,
    "url": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/video/52353cac347a5b95ae6272dfdc41d633.mp4",
    "add_time": "2021-06-03 17:55:22",
    "user_no": 7156912,
    "nickname": "终晓骞7156912"
    }
    ],
    "first_page_url": "http://local.qipaoadmin/userChange/userVideo?page=1",
    "from": 1,
    "last_page": 1,
    "last_page_url": "http://local.qipaoadmin/userChange/userVideo?page=1",
    "next_page_url": null,
    "path": "http://local.qipaoadmin/userChange/userVideo",
    "per_page": 10,
    "prev_page_url": null,
    "to": 1,
    "total": 1
    }
    }
     */
    public function userVideoList(Request $request)
    {
        $userNo = $request->user_no; //用户号
        $perPage = $request->per_page ?: 10; //每页显示条数

        $where = [];
        if ($userNo) {
            $user = app('model_user')->select('user_id')->where('user_no', $userNo)->where('deleted', 0)->first();
            if ($user) {
                $where['user_id'] = $user->user_id;
            } else {
                $where['user_id'] = 0;
            }
        }

        $list = app('model_user_video')
            ->select('id', 'user_id', 'url', 'add_time')
            ->where($where)
            ->where('status', 1)
            ->orderBy('id', 'desc')
            ->paginate($perPage);
        foreach ($list as &$v) {
            $v->add_time = date('Y-m-d H:i:s', $v->add_time);
            //查询用户昵称和用户号
            $userData = app('model_user_data')->select('user_code', 'nickname')->where('user_id', $v->user_id)->first();
            $v->user_no = $userData->user_code;
            $v->nickname = $userData->nickname;
        }
        return Response::sendData($list);
    }

    /**
     * @api {Delete} /userChange/userVideo 删除用户视频
     *
     * @apiGroup 补充接口-平台审核
     *
     * @apiParam {Int} id 记录id
     *
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": []
     */
    public function delUserVideo(Request $request)
    {
        $id = $request->id;

        $photo = app('model_user_video')->where('id', $id)->first();
        if (empty($photo)) {
            throw new BasicException(10001);
        }

        DB::beginTransaction();
        try {
            app('model_user_video')->where('id', $id)->update(['status' => 0, 'del_time' => time()]);
            app('model_user_data')->where('user_id', $photo->user_id)->update(['vedio' => '', 'vedio_cover' => '']);

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, '删除失败');
        }
    }
}
